package com.tarena.lbs.user.dao.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.user.dao.mapper.UserGroupMapper;
import com.tarena.lbs.user.dao.repository.UserGroupRepository;
import com.tarena.lbs.user.pojo.po.UserGroupPO;
import com.tarena.lbs.user.pojo.query.UserGroupQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.List;

@Repository
public class UserGroupRepositoryImpl implements UserGroupRepository {

    @Autowired
    private UserGroupMapper userGroupMapper;

    @Override
    public List<UserGroupPO> getUserGroupsByBusinessId(Integer businessId) {
        QueryWrapper<UserGroupPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("business_id", businessId);
        queryWrapper.orderByDesc("create_at");
        return userGroupMapper.selectList(queryWrapper);
    }

    @Override
    public PageInfo<UserGroupPO> pageList(UserGroupQuery query) {
        QueryWrapper<UserGroupPO> queryWrapper = assembleUserGroupQuery(query);
        // 启动分页
        PageHelper.startPage(query.getPageNo(), query.getPageSize());
        // 执行查询
        List<UserGroupPO> userGroups = userGroupMapper.selectList(queryWrapper);
        // 封装分页信息
        return new PageInfo<>(userGroups);
    }

    @Override
    public void save(UserGroupPO userGroupPO) {
        userGroupMapper.insert(userGroupPO);
    }

    @Override
    public UserGroupPO getById(Integer id) {
        return userGroupMapper.selectById(id);
    }

    /**
     * 组装查询条件
     */
    private QueryWrapper<UserGroupPO> assembleUserGroupQuery(UserGroupQuery query) {
        QueryWrapper<UserGroupPO> queryWrapper = new QueryWrapper<>();
        
        // 商家ID条件
        if (query.getBusinessId() != null) {
            queryWrapper.eq("business_id", query.getBusinessId());
        }
        
        // 分组名称模糊查询
        if (StringUtils.hasText(query.getGroupName())) {
            queryWrapper.like("group_name", query.getGroupName());
        }
        
        // 标签ID条件
        if (StringUtils.hasText(query.getTagIds())) {
            queryWrapper.like("tag_ids", query.getTagIds());
        }
        
        // 发布状态条件（这里需要根据实际业务逻辑调整）
        if (StringUtils.hasText(query.getPublishStatus())) {
            // 假设发布状态存储在某个字段中，这里需要根据实际表结构调整
            // queryWrapper.eq("publish_status", query.getPublishStatus());
        }
        
        // 创建时间范围查询
        if (query.getStartTime() != null) {
            queryWrapper.ge("create_at", query.getStartTime());
        }
        if (query.getEndTime() != null) {
            queryWrapper.le("create_at", query.getEndTime());
        }
        
        // 按创建时间倒序排列
        queryWrapper.orderByDesc("create_at");
        
        return queryWrapper;
    }
}
